#include "graphic_shader.h"
#include "input_file_manager.h"
#include "input_file.h"
/*--------------------------------------------------------------------------------*/
PFNGLCREATESHADERPROC
	GRAPHIC_SHADER::glCreateShader = NULL;
PFNGLDELETESHADERPROC
	GRAPHIC_SHADER::glDeleteShader = NULL;
PFNGLSHADERSOURCEPROC
	GRAPHIC_SHADER::glShaderSource = NULL;
PFNGLCOMPILESHADERPROC
	GRAPHIC_SHADER::glCompileShader = NULL;
PFNGLGETSHADERIVPROC
	GRAPHIC_SHADER::glGetShaderiv = NULL;
PFNGLGETSHADERINFOLOGPROC
	GRAPHIC_SHADER::glGetShaderInfoLog = NULL;
/*--------------------------------------------------------------------------------*/
VOID GRAPHIC_SHADER::Initialize( const TEXT & source_file_name, const GRAPHIC_SHADER::TYPE type )
{
	INPUT_FILE::REF
		file;
	CHAR
		*ptr;

	DEBUG_Require( !Id );
	DEBUG_Require( INPUT_FILE_MANAGER_DoesFileExist( source_file_name ) );

	Type = type;
	file = INPUT_FILE_MANAGER_GetFile( source_file_name );

	switch( Type )
	{
		case TYPE_VertexShader:
			Id = glCreateShader( GL_VERTEX_SHADER );
		break;

		case TYPE_PixelShader:
			Id = glCreateShader( GL_FRAGMENT_SHADER );
		break;
	}

	file->Open();

	ptr = ( CHAR *) file->GetContent().GetArray();

	glShaderSource( Id, 1, ( const GLchar** ) & ptr, NULL );
	glCompileShader( Id );

	if( !IsCompiled() )
	{
		DEBUG_Log( "Error while compiling shader :\n" );
		DEBUG_Log( GetInfoLog() );
	}
	else
	{
		DEBUG_Log( "Shader loaded \"" + source_file_name + "\"\n" );
	}
}
/*--------------------------------------------------------------------------------*/
BOOL GRAPHIC_SHADER::IsCompiled() const
{
	GLint
		compile_status = GL_TRUE;

	glGetShaderiv( Id, GL_COMPILE_STATUS, &compile_status);

	if( compile_status != GL_TRUE )
	{
		return false;
	}

	return true;
}
/*--------------------------------------------------------------------------------*/
const TEXT GRAPHIC_SHADER::GetInfoLog() const
{
	GLint
		log_size;
	CHAR
		buffer[ 1024 ];

	glGetShaderiv( Id, GL_INFO_LOG_LENGTH, &log_size );

	glGetShaderInfoLog( Id, 1024, &log_size, buffer);

	return TEXT( buffer );
}
/*--------------------------------------------------------------------------------*/
